from rest_framework.decorators import action
from rest_framework.response import Response
from rest_framework.viewsets import ReadOnlyModelViewSet
from meiduo_admin.serializer.orders import OrderSerializer
from rest_framework.permissions import IsAdminUser
from meiduo_admin.utils import PageNum
from orders.models import OrderInfo



# 获取多个和一个订单数据
class OrderView(ReadOnlyModelViewSet):

    # 指定权限
    permission_classes = [IsAdminUser]
    # 指定序列化器
    serializer_class = OrderSerializer
    # 指定查询集
    queryset = OrderInfo.objects.all()
    # 指定分页器
    pagination_class = PageNum

    # 重写get_queryset方法根据根据前端传递的keyword参数,返回不同的数据
    def get_queryset(self):
        # 获取前端的keyword参数
        keyword = self.request.query_params.get('keyword')

        if keyword == '' or keyword is None:
            return OrderInfo.objects.all()
        else:
            # order_id__contains 模糊查询 包含
            return OrderInfo.objects.filter(order_id__contains=keyword)
    # Permission
    # 修改订单状态
    @action(methods=['put'],detail=True)
    def status(self,request,pk):
        # 查询订单对象
        try:
            order = OrderInfo.objects.get(order_id=pk)
        except:
            return Response({'erroe':'无效的订单编号'})
        # 修改订单状态
        status = request.data.get('status')
        if status is None:
            return Response({'error':'缺少订单状态'})
        order.status = status
        order.save()
        # 返回订单信息
        ser = self.get_serializer(order)
        return Response(ser.data)
